<template>
  <template v-if="tagType">
    <el-tag :type="tagType" :size="tagSize">{{ label }}</el-tag>
  </template>
  <template v-else>
    <span>{{ label }}</span>
  </template>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { useUserCacheStore } from "@/store/modules/user-cache.store.js";

defineOptions({
  name: "UserLabel",
  inheritAttrs: false,
});

const props = defineProps({
  modelValue: [String, Number], // 用户ID
  size: {
    type: String,
    default: "default", // 标签大小
  },
  showTag: {
    type: Boolean,
    default: false, // 是否显示为标签
  },
  tagType: {
    type: String,
    default: "primary", // 标签类型
  },
});

const label = ref("");
const tagType = ref(); // 标签类型
const tagSize = ref(props.size); // 标签大小

const userCacheStore = useUserCacheStore();

/**
 * 更新用户名显示
 */
const updateLabel = async () => {
  if (!props.modelValue) {
    label.value = "-";
    return;
  }

  try {
    const userInfo = await userCacheStore.getUserInfo(props.modelValue);
    if (userInfo) {
      label.value = userInfo.nickname || userInfo.username || "未知用户";
    } else {
      label.value = "未知用户";
    }
  } catch (error) {
    console.error("UserLabel: 获取用户信息失败", error);
    label.value = "未知用户";
  }

  // 设置标签类型
  if (props.showTag) {
    tagType.value = props.tagType;
  } else {
    tagType.value = null;
  }
};

watch(() => props.modelValue, updateLabel);
watch(() => props.showTag, updateLabel);
watch(() => props.tagType, updateLabel);

onMounted(updateLabel);
</script>

<style scoped>
span {
  color: #606266;
}
</style>
